# -*- coding: utf-8 -*-

#This file is part of pyLot library.
#
# pyLot is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# pyLot is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with pyLot.  If not, see <http://www.gnu.org/licenses/>.

__author__ = u'Pierre Puiseux, Guillaume Baty'
__copyright__ = u"Copyright 2011-2012 (C) andheo, Université de Pau et des Pays de l'Adour"
__credits__ = [u'Pierre Puiseux', u'Guillaume Baty']
__license__ = "GNU Lesser General Public License"

__all__ = [
  'GuiExtensibleToolBox',
  'MOD_SMARTPHONE',
  'MOD_MULTIPLE_WIN',
  'MOD_UNIQUE_WIN',
  'MOD_DOCK',
  'MOD_MULTITASK',
  'connect_extensible_toolbox_signals',
]

import logging
import sys

from Qt4 import QtCore, QtGui, QtWebKit
from Qt4.QtCore import SIGNAL


from pyLot.core import (Path, UserConfigDir, ENCODING,
                        StatusBarLoggingHandler, get_data, clean_memory)

from pyLot.application import APPLICATION

from _pylot.qtgui.tools import (widget_state_import_raw, widget_state_export_raw,
                                generate_pyfile_from_uifile, Dialog)
from _pylot.qtgui import styles
from _pylot.qtgui.widgets.gui_dialog import GuiDialog
from _pylot.qtgui.widgets.about import About

from _pylot.qtgui.qprocesshandler import QProcessHandler

from .mainwin_common import MainWinCommon

from .options import *

_APP_PREF = ''
LOGGER = logging.getLogger(u'pyLot.qtgui')

def create_toggle_visibility_action(widget, name, title, parent):
  action = QtGui.QAction(title, parent)
  action.setObjectName('action_show_%s' % name)
  action.setCheckable(True)
  action.toggled.connect(widget.setVisible)
  try :
    widget.visibilityChanged.connect(action.setChecked)
  except AttributeError : #Qt4.6 QToolbar has no visibilityChanged
    action.setEnabled(False)
    action.setToolTip(u'You must install Qt >=4.7 to enable this action')
  return action

def connect_extensible_toolbox_signals(caller, receiver):
    for request in [
      'displayDocRequest',
      'setProgressBarFormatRequest',
      'startProgressBarRequest',
      'stopProgressBarRequest',
      'setProgressBarValueRequest',
      ]:

      # caller
      try :
        signal = getattr(caller, request)
      except AttributeError:
        signal = None

      try :
        slot = getattr(receiver, request.replace('Request', ''))
      except AttributeError :
        slot = None

      if signal and slot :
        signal.connect(slot)

generate_pyfile_from_uifile(__name__)
from .designer._gui_ext_toolbox import Ui_WinToolBox
class GuiExtensibleToolBox(QtGui.QMainWindow, Ui_WinToolBox, MainWinCommon):
  u"""

  request signals:
  
  These signals are used by toolwidgets to ask to do special graphical actions.
  This allow to use application common parts (process, outputs or documentation 
  panels for example) without creating a dependency between MainApp and
  widgets. This signal are called "request" because GuiExtensibleToolBox can
  choose to ignore them or add them to a queue, for example to avoid conflicts.
 
  Supports Request Signals are ...

    - displayDocRequest(unicode url) : display doc located in url in documentation panel
    - undockRequest(QWidget widget): undock widget
    - redockRequest(QWidget widget): redock widget
    - setProgressBarFormatRequest(unicode fmt) : see QProgressBar.setFormat
    - startProgressBarRequest(int minimum, int maximum) : shows and initializes progress bar to minimum
    - stopProgressBarRequest() : hide progress bar
    - setProgressBarValueRequest(int step)  : set progress in percent (type int, between 0 and 100)

  Non graphical common actions are done using pyLot.application module

  When user clicks on a ToolWidget icon, GuiExtensibleToolBox do these actions:
  (only at first click) :
    - create toolwidget object "app"
    - app.readSettings(userconf_dir, recursive)
    - app.translate()
    - app.switchUserLevel()
    - app.decorate()
    - connect request signals
  """

  # Defined only for testing purpose
  startProgressBarRequest = QtCore.Signal(int, int)
  stopProgressBarRequest = QtCore.Signal()
  setProgressBarFormatRequest = QtCore.Signal(unicode)
  setProgressBarValueRequest = QtCore.Signal(int)

  """
  TestToolkit : 
    - 0 no test toolkit (default)
    - 1 enable test toolkit
  """
  TestToolkit = None


  def __init__ (self, mode=MOD_SMARTPHONE,
                process_widget=None, logo=None,
                about_widgets=[], parent=None):
    self._about_widgets = about_widgets + [About]
    self._logo_path = logo

    QtGui.QMainWindow.__init__(self, parent)
    MainWinCommon.__init__(self)
    self.setupUi(self)

    self.app = APPLICATION
    self.conf_dir = APPLICATION.home

    self.parse_dict = None

    # Load applications
    self._go_app_actions = []

    # DOCK PART
    self._dock_contents = []
    self._current_docks = []
    self._show_dock_actions = []

    # TB PART
    self._show_tb_actions = []

    # TOOL WIDGETS
    self.pb_applis = {}
    self.widget2module = {}
    self.button2widget = {}
    self.toolwidget_classes = {}

    # temporary disabled because do not work with pyside
    process_handler = QProcessHandler()
#    process_handler.readSettings(settings, common_settings)
    self.app.setProcessHandler(process_handler)
    self.process_widget = process_handler.getProcessHandlerWidget()
    self.append(self.process_widget)
    dock = self.dockWidget(self.process_widget)
    dock.hide()

    self.dock_go_app = self.dockWidget(self.frame_appview_icons, u'Application selector')
#    self.dock_frame

    self.logger_statusbar = StatusBarLoggingHandler(self.statusbar)
    self.logger_statusbar.setLevel(logging.INFO)

    self.progress_bar = QtGui.QProgressBar()
    self.progress_bar.hide()
    self.progress_bar.setMinimum(0)
    self.progress_bar.setMaximum(100)
    self.statusbar.addWidget(self.progress_bar)

    LOGGER.addHandler(self.logger_statusbar)

    self._mode = mode
    self._first_load = True
    self._toolwidgets = []

    self._loadPlugins()

    if self._mode == MOD_MULTIPLE_WIN:
      self._initModMultipleWins()
    elif self._mode == MOD_SMARTPHONE :
      self._initModSmartphone()
    elif self._mode in (MOD_UNIQUE_WIN, MOD_MULTITASK) :
      self._initModUnique()
    elif self._mode == MOD_DOCK :
      self._initModDock()

    self.doc = QtWebKit.QWebView()
    self.dock_doc = self.dockWidget(self.doc, u'Documentation')
    self.action_show_dock_doc = self._show_dock_actions[-1]
    self.dock_doc.hide()

    # current tool widget
    self._current = None

    QtGui.QToolTip.setFont(styles.font_fixed)
#    add_developer_infos(self)

    self._createMenus()
    self._createToolBars()
    self._createActions()
    self._createConnexions()

    self.autoSetToolBars(self)

    self.translate()
    self.switchUserLevel()
    self.decorate()
    self.fineTune()

    clean_memory()

    if self.TestToolkit is None :
      self.TestToolkit = 0

  def autoSetToolBars(self, widget):
    for tool_bar in widget.tool_bars :
      self.addToolBar(tool_bar)

  def _createConnexions(self):
    MainWinCommon._createConnexions(self)
    self.action_documentation.triggered.connect(self.displayDoc)
    self.action_quit.triggered.connect(self.actionQuit)

  def _fineTune(self):
    self.doc.setSizePolicy(QtGui.QSizePolicy(styles.MinimumExpanding, styles.Minimum))
    self.doc.setMinimumSize(300, 200)
    self.displayDoc()
    if self._logo_path :
      self.logo_img.setPixmap(QtGui.QIcon(self._logo_path).pixmap(QtCore.QSize(300, 300)))
#    self.tool_bar_go_app.hide()

  def _createActions(self):
    MainWinCommon._createActions(self)

    self._about_actions = {}
    for widget in self._about_widgets :
      action = QtGui.QAction(widget.alias, self)
      action.setObjectName('about_%s' % widget.name)
      action.triggered.connect(self.actionDisplayAboutWidgets)
      self._about_actions[action] = widget

    for tool_bar in self._tool_bars :
      action = create_toggle_visibility_action(tool_bar, tool_bar.objectName(),
                                               tool_bar.windowTitle(), self)
      self._show_tb_actions.append(action)

  def _createMenus(self):
    # Menu objects are created in ui designer file
    # just add them to toolwidget
    for menu in [
      self.menu_display,
      self.menu_edit,
      self.menu_help,
      self.menu_file,
      self.menu_scripts,
      self.menu_display,
      self.menu_go_app,
     ] :
      self.addMenu_(menu)

  def _createToolBars(self):
    self.tool_bar_go_app = QtGui.QToolBar(u'Application selector toolbar')
    self.addToolBar_(self.tool_bar_go_app)

  def _fillToolBars(self, level):
    MainWinCommon._fillToolBars(self, level)
    self.tool_bar_go_app.addActions(self._go_app_actions)

  def _preFillMenus(self, level):
    u"""
    Clear menus and fill GuiExtensibleToolBox action that must be displayed 
    **before** toolwidget aactions
    """
    # clear all menus because manus may contain toolwidget actions.
    for menu in self._menus :
      menu.clear()

    self._fill(self.menu_go_app, self._go_app_actions, clear=False)

#    self._fill(self.menu_file, [
#      self.action_save,
#      self.action_load,
#      u'-',
#      self.action_save_as,
#      self.action_load_from,
#      ])

    actions = [self.menu_go_app, u'Docks']
    actions += self._show_dock_actions
    actions += [u'Barres d\'outils']
    actions += self._show_tb_actions
    self._fill(self.menu_display, actions, clear=False)

    self._fill(self.menu_help, [
      self.action_show_dock_doc,
      ] + self._about_actions.keys(), clear=False)

#    self._fill(self.menu_scripts, [
#      self.action_start_recorder,
#      self.action_stop_recorder
#      ])

  def _postFillMenus(self, level):
    u"""
    Fill GuiExtensibleToolBox action that must be displayed 
    **after** toolwidget aactions
    """
    self._fill(self.menu_file, [
      u'-',
      self.action_quit,
      ], clear=False)

    self._fill(self.menu_edit, [
      u'-',
      self.action_preferences,
      ], clear=False)

  def _loadPlugins(self):

    for i, widget_class in enumerate(self.pm.get_extensions('pyLot.qtgui.toolwidgets')):
      widget = widget_class
      identifier = widget.identifier
      title = widget.title

      pb = QtGui.QPushButton()
      size = 96
      pb.setGeometry(QtCore.QRect(size, size, size, size))

      pb.setSizePolicy(styles.FIXED)
      pb.setMinimumSize(QtCore.QSize(1.05 * size, 1.05 * size))
      pb.setMaximumSize(QtCore.QSize(1.05 * size, 1.05 * size))
      pb.setIconSize(QtCore.QSize(size, size))
      pb.setFlat(True)

      pb.setWindowTitle(title)
      action = QtGui.QAction(title, self)

      if widget_class.main_icon :
        pb.setIcon(QtGui.QIcon(widget_class.main_icon))
        action.setIcon(QtGui.QIcon(widget_class.main_icon))
      else :
        pb.setText(widget.title)

      tt = u'plugin %s (id: %s)' % (title, identifier.decode(ENCODING))
      pb.setToolTip(tt)

      ncol = 2
      self.connect(pb, SIGNAL('clicked()'), self.showAppli)
      self.connect(action, SIGNAL('triggered()'), self.showAppli)
      self.pb_applis[identifier] = pb
      self.widget2module[pb] = identifier
      self.widget2module[action] = identifier
      self.toolwidget_classes[identifier] = widget_class
      self.layout_appview_icons.addWidget(pb, i / ncol, i % ncol)

      self._go_app_actions.append(action)

  def _initModMultipleWins(self):
    self.frame_appview.setSizePolicy(styles.HSMALL)
    self.setSizePolicy(styles.HSMALL)
    self.mdiArea.hide()
    self.resize(QtCore.QSize(10, 10))
    self.line.hide()

  def _initModSmartphone(self):
    pass

  def _initModUnique(self):
    self.menubar.hide()
    self.frame_appview.setSizePolicy(styles.HSMALL)
    self.line.hide()
    self.resize(QtCore.QSize(10, 10))

  def _initModDock(self):
    self.resize(QtCore.QSize(10, 10))
    self.line.hide()

  def _decorate(self):
    self._default_style = self.styleSheet()
    #self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
#    self.setAttribute(QtCore.Qt.WA_PaintOnScreen, True)
#    self.setAttribute(QtCore.Qt.WA_OpaquePaintEvent, True)
#    self.setAttribute(QtCore.Qt.WA_TranslucentBackground, True)
    # Autre possibilité : http://qt.developpez.com/tutoriels/braindeadbzh/customwindow/


  def _addSubWindow(self, widget):
    u"""
    creates a new QMdiSubWindow and adds it to self.mdiArea
    """
    subwidget = QtGui.QMdiSubWindow()

    scroll = QtGui.QScrollArea()
    scroll.setFrameShape(QtGui.QFrame.NoFrame)
    scroll.setLineWidth(0)
    scroll.setWidgetResizable(True)
    scroll.setWidget(widget)

    subwidget.setWidget(scroll)
    subwidget.setWindowTitle(widget.windowTitle())
    self.mdiArea.addSubWindow(subwidget)

    return subwidget

  def exportAppliState(self, filepath=None):
    if self._current :
      if filepath is None :
        name = self._current[1].objectName()
        filepath = UserConfigDir(self.conf_dir, u'%s.dump' % name)
      else :
        filepath = Path(filepath)
      widget_state_export_raw(self._current[1], filepath)

  def importAppliState(self, filepath=None):
    if self._current :
      if filepath is None :
        name = self._current[1].objectName()
        filepath = UserConfigDir(self.conf_dir, u'%s.dump' % name)
      else :
        filepath = Path(filepath)
      if filepath.isfile():
        widget_state_import_raw(self._current[1], filepath)

  def initAppli(self, app):
    app.init()
    connect_extensible_toolbox_signals(app, self)
    app.translate(locale=None, force=True, recursive=True)
    app.switchUserLevel()
    app.readSettings(self.app.home)
    app.decorate()
    app.fineTune()

  def _fillMenus(self, level):
    # Clear **menu bar**
    self.menubar.clear() # Clear menu bar
    # Clear **menus**
    self._preFillMenus(level) # Reset menus to default menus

    # Add menus that must be displayed before toolwidget menus
    self.menubar.addMenu(self.menu_file)
    self.menubar.addMenu(self.menu_edit)
    self.menubar.addMenu(self.menu_display)
#    self.menubar.addMenu(self.menu_scripts)
    # Add special menus defined in GuiExtensibleToolBox built in widgets
    for widget in self :
      self.fillMenuBarFromWidget(widget)

    if self._current :
      container, widget = self._current
      self.fillMenuBarFromWidget(widget)

    self._postFillMenus(level)

    # Add last menu "Help"
    self.menubar.addMenu(self.menu_help)

  def fillMenuBarFromWidget(self, widget):
    for menu in widget.menus :
      menu_name = unicode(menu.objectName()).lower()
      if not menu_name.startswith(u'menu_') :
        menu_name = u'menu_%s' % menu_name
      if menu_name in (u'menu_file', u'menu_edit',
                       u'menu_help', u'menu_display') :
        local_menu = getattr(self, menu_name)
        local_menu.addSeparator()
        local_menu.addActions(menu.actions())
      else :
        self.menubar.addMenu(menu)

  def loadAppli(self, identifier=None):

    self._previous = self._current

    if identifier :
      name = identifier
    else :
      sender = self.sender()
      name = self.widget2module[sender]

    try :
      subwidget, app = self.button2widget[name]
    except KeyError:
      widget_class = self.toolwidget_classes[name]
      if self.parse_dict :
        self.parse_dict.parse_before()
        self.parse_dict.parse_class(widget_class)
      app = widget_class()
      if self.parse_dict :
        self.parse_dict.parse_instance(app)
      self._toolwidgets.append(app)

      if self._mode == MOD_MULTIPLE_WIN : # Pas de parents
        self.button2widget[name] = (app, app)
      elif self._mode == MOD_SMARTPHONE :
        self.button2widget[name] = (app, app)
        self.layout_frame_appview.addWidget(app)
      elif self._mode == MOD_UNIQUE_WIN : # Parent MDI
        subwidget = self._addSubWindow(app)
        self.button2widget[name] = (subwidget, app)
      elif self._mode == MOD_DOCK :
        subwidget = QtGui.QDockWidget()
        subwidget.setWidget(app)
        self.addDockWidget(QtCore.Qt.RightDockWidgetArea, subwidget)
        self.button2widget[name] = (subwidget, app)
        subwidget.setWindowTitle(name)
      elif self._mode == MOD_MULTITASK :
        raise NotImplementedError

      for dock, level in app.docks:
        self.dockWidget(dock)

      self.initAppli(app)
      if self.parse_dict :
        self.parse_dict.parse_after(app)
#      add_developer_infos(app, text=self.toolTip())
    app.refresh()
    self._current = self.button2widget[name]

    return self._current

  def showAppli(self, identifier=None):
    if self._first_load is True :
      self.logo.close()
      del self.logo
      if self._mode == MOD_UNIQUE_WIN :
        self.mdiArea.show()
        self.menubar.show()
        self.resize(QtCore.QSize(1000, 800))
      self.dock_go_app.hide()
      self._first_load = False

    subwidget, app = self.loadAppli(identifier)

    if self._mode == MOD_MULTITASK :
      raise NotImplementedError
#      subwidget = QtGui.QMdiSubWindow()
#      subwidget.setWidget(widget_class())
#      subwidget.setWindowTitle(name)
#      self.mdiArea.addSubWindow(subwidget)
#      subwidget.show()

    elif self._mode == MOD_SMARTPHONE :

      # Hide previous widget and display new one
      if self._previous != self._current :
        # Hide previous
        if self._previous :
          container, widget = self._previous
          container.hide()
          docks = [dock for dock, level in widget.docks]
          for dock_content in self._current_docks :
            if dock_content in docks :
              dock_content.parent().hide()

        # Show current
        container, widget = self._current
        for dock_content, level in  widget.docks :
          dock_content.parent().show()
          dock_content.show()
        widget.show()
        container.show()

    else :
      if app.isVisible() :
        app.hide()
      else :
        app.show()
        if self._mode == MOD_UNIQUE_WIN :
          app.widget().show()

    self.translate()
    self.switchUserLevel()

    if self.TestToolkit :
      app.test = app.createTestBox()
      app.test.show()

  def displayDoc(self, url=None):
    if url :
      self.doc.load(QtCore.QUrl(url))
    else :
      self.doc.load(QtCore.QUrl(get_data('_pylot.data', u'doc/WELCOME.txt')))


  def readyToClose(self):
    close = True
    for widget in self:
      if widget.readyToClose() is False :
        close = False
    for widget in self._toolwidgets :
      if widget.readyToClose() is False:
        close = False

    return self._readyToClose() and close

  def closeEvent(self, event):
    if self.readyToClose():
      event.accept()
      self.saveAndQuit()
    else :
      event.ignore()

  def actionDisplayPreferences(self):

    if self._current :
      tool_pref = self._current[1].createPreferenceWidget(self.handler.level)
      if tool_pref is None :
        tool_pref = QtGui.QLabel(u'No preferences for %s' % self._current[1].title)
      dialog = GuiDialog(tool_pref)
      dialog.exec_()
      tool_pref.close()
      del tool_pref

  def saveAndQuit(self):

    for subwidget, widget in self.button2widget.values() :
      widget.writeSettings(self.app.home, True)
      widget.close()
    for widget in self :
      widget.writeSettings(self.app.home, True)
      widget.close()


  def dockWidget(self, widget, title=u'Dock'):
    self.connect(widget, SIGNAL('undockRequested'), self.undockWidget)
    self.connect(widget, SIGNAL('redockRequested'), self.redockWidget)

    dock_name = widget.objectName()
    dock_name = u'dockWidget%s' % dock_name

    dock = QtGui.QDockWidget(self)
    dock.setFeatures(QtGui.QDockWidget.AllDockWidgetFeatures)
    dock.setObjectName(dock_name)
    dock.setWidget(widget)

    if widget not in self._dock_contents :
      self._dock_contents.append(widget)
      self._docks.append(dock)

    action = create_toggle_visibility_action(dock, dock_name, title, self)
    self._show_dock_actions.append(action)

    self.addDockWidget_(widget)
    return dock

  def addDockWidget_(self, dock_content, show=True):
    u"""
    :param show: if True, show dock, else only make it available
    """
    if dock_content not in self._current_docks :
      dock = dock_content.parent()
#      if dock_content.windowTitle() :
#        msg = tr_(u'New dock "%s" is available\n') % dock_content.windowTitle()
#      else :
#        msg = tr_(u'A New dock is available\n')
#      self.handler.io.writeStatus(msg, style=u'warn')
      if show is True :
        dock.show()
      self.addDockWidget(QtCore.Qt.LeftDockWidgetArea, dock)
      self._current_docks.append(dock_content)

  def removeDockWidget_(self, dock_content):
    if dock_content in self._current_docks :
      dock = dock_content.parent()
      dock.hide()
      self.removeDockWidget(dock)
      self._current_docks.remove(dock_content)

  def undockWidget(self, widget):
    if widget in self._current_docks:
      self.removeDockWidget_(widget)
    elif widget in self._current_tabs :
      self.removeTab_(widget)

  def redockWidget(self, widget, show=True):
    if self._default_dock_mode in ('tabs', 'process_and_tabs') :
      self.addTab_(widget)
    elif self._default_dock_mode in ('docks', 'process_and_docks') :
      self.addDockWidget_(widget, show)

  def startProgressBar(self, minimum, maximum):
    self.progress_bar.setValue(minimum)
    self.progress_bar.setMinimum(minimum)
    self.progress_bar.setMaximum(maximum)
    self.progress_bar.show()

  def stopProgressBar(self):
    self.progress_bar.setValue(self.progress_bar.maximum())
    import time
    time.sleep(0.5)
    self.progress_bar.hide()

  def setProgressBarValue(self, step):
    self.progress_bar.setValue(step)

  def setProgressBarFormat(self, fmt):
    self.progress_bar.setFormat(fmt)

  def actionDisplayAboutWidgets(self):
    widget_class = self._about_actions[self.sender()]
    widget = widget_class()
    dialog = Dialog(widget)
    dialog.exec_()


  def _translate(self):
    MainWinCommon._translate(self)

    self._setTexts([
      (self.frame_appview_icons, tr_(u'Application selector')),
      (self.doc, tr_(u'Documentation')),
      ])

#    self._setTexts([
#      (self.action_preferences, tr_(u'Preferences')),
#      (self.action_retranslate_ui, tr_(u'Retranslate GUI')),
#      (self.action_quit, tr_(u'Quit')),
#      (self.action_whatsthis, tr_(u'What\'s this ?')),
#      (self.action_run_script, tr_(u'Run script')),
#      (self.action_run_last_script, tr_(u'Run last script')),
#
#      (self.menu_edit, tr_(u'&Edit')),
#      (self.menu_file, tr_(u'&File')),
#      (self.menu_help, tr_(u'&Help')),
#      (self.menu_scripts, tr_(u'&Scripts')),
#      ])

    for dock_content in self._current_docks :
      dock_alias = dock_content.windowTitle()
      dock_content.parent().setWindowTitle(dock_alias)

#    for idx in range(self.tab_bar.count()):
#      tab = self.tab_bar.widget(idx)
#      self.tab_bar.setTabText(idx, tab.windowTitle())
#
#    self._setTexts([
#      (self.action_whatsthis, tr_(u'Shift+F1')),
#      (self.action_run_last_script, tr_(u'Ctrl+Shift+R')),
#      ], field=u'shortcut')

  def _test_01_ProgressBar_meth(self):
    connect_extensible_toolbox_signals(self, self)
    import time
    self.startProgressBarRequest.emit(0, 0)
    for i in range(100):
      self.setProgressBarValueRequest.emit(i + 1)
      time.sleep(0.01)
    self.stopProgressBarRequest.emit()

  def setToolwidgetCliModifiers(self, parse_dict):
    self.parse_dict = parse_dict


if __name__ == "__main__":
  app = QtGui.QApplication(sys.argv)

  try :
    mode = sys.argv[1]
  except IndexError :
    mode = MOD_SMARTPHONE
  else :
    mode = int(mode)

  win = GuiExtensibleToolBox(mode)
  win.show()
  sys.exit(app.exec_())

